/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.web.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.spring.web.servlet.view.JsonView;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.User;
import org.cx1.model.utils.EmailInvitee;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.model.utils.SystemProperties;
import org.cx1.service.api.IEmailService;
import org.cx1.service.api.IInquiryService;
import org.cx1.service.api.IInviteService;
import org.cx1.service.api.IUserService;
import org.cx1.service.impl.DUserService;
import org.cx1.service.impl.MEmailService;
import org.cx1.service.impl.MInquiryService;
import org.cx1.service.impl.MInviteService;
import org.cx1.service.impl.MUserService;
import org.cx1.web.controller.action.InquiryAction;
import org.cx1.web.controller.action.InviteAction;
import org.cx1.web.utils.PasswordGen;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author ECH
 */
public class InviteControllerWS extends BaseController {
    
    //private IUserService userService = new MUserService();
    
    private IUserService userService = new DUserService();
    private IInviteService inviteService = new MInviteService();
    private IEmailService emailService = new MEmailService();
    
    public InviteControllerWS() {
        
    }
    
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
                                                 HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView();
        Map map = new HashMap();        
        
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        if (ServletFileUpload.isMultipartContent(request)) {
            parameterMap = this.getMultipartFormParams(request);
        } 
        else {
            parameterMap = this.getFormParams(request);
        }
        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        int action = StringUtils.isEmpty(formfields.get("a")) ? 0 : Integer.parseInt(formfields.get("a"));
        
        switch (action) {         
            case InviteAction.CREATE: {
                create(mav, map, request);
                break;
            }
            case InviteAction.CHECK_EMAIL_EXISTING: {
                checkEmailExisting(mav, map, request);
                break;
            }
            case InviteAction.CREATE_EMAIL_INVITEE: {
                createEmailInvitee(mav, map, request);
                break;
            }
            default: {
                break;
            }
        }          
                
        map.put("host", SystemProperties.SYSTEM_HOST);
        map.put("port", SystemProperties.SYSTEM_PORT);
        
        mav.setView(new JsonView());
        mav.addObject("model", map);
        return mav;
    }    
    
    private void create(ModelAndView mav, Map map, HttpServletRequest request) {
        boolean success = false;
                
        String firstName = StringUtils.isEmpty(request.getParameter("firstName")) ? "" : request.getParameter("firstName");
        String lastName = StringUtils.isEmpty(request.getParameter("lastName")) ? "" : request.getParameter("lastName");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String type = request.getParameter("type");    
        String area = request.getParameter("area");       
        
        String remoteAddr = request.getRemoteAddr();
        
        //ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        //reCaptcha.setPrivateKey("6LcJpegSAAAAAJzGZN-OWFnq48drxH-vmu0zYHkE");
        //String challenge = request.getParameter("recaptcha_challenge_field");
        //String uresponse = request.getParameter("recaptcha_response_field");
        //ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        //if (reCaptchaResponse.isValid()) {
        if (true) {
            success = true;
            
            inviteService.create(firstName, email, type, area);
            
            User user = new User();
            //String password = PasswordGen.generatePassworf();
            
            user.setEmail(email);
            user.setEmailPrimary(email);
            user.setPassword(password);
            
            user.setFirstName(firstName);
            user.setLastName(lastName);
                        
            ServiceResponse<String> response = userService.create(user);
            User created = userService.readByEmail(email).getResponse();
            if (created != null) {
                emailService.sendSignupConfirmation(created.getFirstName(), created.getEmail(), created.getPassword());
            }            
        } 
        else {
            success = false;
        }        
        map.put("success", success);
    }
    
    
    private void checkEmailExisting(ModelAndView mav, Map map, HttpServletRequest request) {
        String email = request.getParameter("email");       
        ServiceResponse<User> response = userService.readByEmail(email);    
        int existing = 0;
        if (response.getResponse() != null) {
            existing = 1;
        }
        map.put("existing", existing);
    }
    
    private void createEmailInvitee(ModelAndView mav, Map map, HttpServletRequest request) {
        boolean success = false;        
        String name = request.getParameter("name");
        String email = request.getParameter("email");      
        
        EmailInvitee emailInvitee = new EmailInvitee();
        emailInvitee.setName(name);
        emailInvitee.setEmail(email);
        
        ServiceResponse<String> response = inviteService.createEmailInvitee(emailInvitee);        
        success = true;
        map.put("success", success);
    }
    
}